package cn.redragon.soa.common.component;

import java.beans.PropertyEditorSupport;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;

public class CustomLocalDateTimeEditor extends PropertyEditorSupport {

    private final DateTimeFormatter formatter;

    public CustomLocalDateTimeEditor(DateTimeFormatter formatter) {
        this.formatter = formatter;
    }

    /**
     * Format the Date as String, using the specified DateFormat.
     */
    @Override
    public String getAsText() {
        LocalDateTime value = (LocalDateTime) getValue();
        return (value != null ? value.format(formatter) : "");
    }

    @Override
    public void setAsText(@Nullable String text) throws IllegalArgumentException {
        if (!StringUtils.hasText(text)) {
            // Treat empty String as null value.
            setValue(null);
        }

        try {
            setValue(LocalDateTime.parse(text, formatter));
        } catch (Exception ex) {
            throw new IllegalArgumentException("Could not parse date: " + ex.getMessage(), ex);
        }

    }
}
